export default {
    name: "printexcel",
	props: {
        bgsx: { type: Object, default: () => ({}) },
        viewcolum: { type: Array, default: () => [] },
        zds: { type: Object, default: () => ({}) },
        allusers: { type: Array, default: () => [] }
	},
    setup(props, { expose }) {
        const user = JSON.parse(localStorage.getItem('user')) || {};
        
        const tablePrint = async (tableData) => {
            const headers = generateHeaders(props.viewcolum, props.zds);
            const data = await processData(tableData, headers);
            if (!data.length) return ElMessage.error('数据为空');
            let tableHtml = generateTableHtml(headers, data, props.bgsx.formname);
            if (window.APP_CONFIG.shuiyin) {
                let txt = window.APP_CONFIG.shuiyin == 'user' ? user.Name : window.APP_CONFIG.shuiyin;
                tableHtml = generateWatermark(txt) + tableHtml;
            }
            ElMessageBox.confirm('请选择单元格内容对齐方式。', '温馨提示', {
                distinguishCancelAndClose: true,
                confirmButtonText: '居中对齐',
                cancelButtonText: '居左对齐',
            }).then(() => print(tableHtml, 'center', user.Name)).catch((action) => { // 接收 action 参数
                if (action === 'cancel') {
                    print(tableHtml, 'left', user.Name); // 取消按钮：居左对齐
                } else if (action === 'close') {
                    ElMessage.info('已取消打印操作');
                }
            });
        }
        
        //获取表头字段
        const generateHeaders = (viewcolum, zds) => {
            return viewcolum.map(k => ({
                field: k,
                displayName: zds[k]
            }))
        }
        
        const processData = async (tableData, headers) => {
            const data =  JSON.parse(JSON.stringify(tableData));
            return Promise.all(data.map(async item => {
                item.cjz = props.allusers.find(u => u.value === item.cjz)?.label || item.cjz;
                item.created_at = window.validators.formatDate(item.created_at);
                item.updated_at = window.validators.formatDate(item.updated_at);
                await Promise.all(headers.map(async ({ field }) => {
                    const fieldConfig = props.bgsx.fields[field];
                    if (!fieldConfig?.type) return;
                    const value = item[field];
                    if (!value) return;
                    item[field] = await processFieldValue(fieldConfig.type, value);
                }))
                return item
            }))
        }
        
        const processFieldValue = async (type, value) => {
            const processors = {
                image: v => processImage(v),
                sczs: v => `<img src="${v}" style="width:50px;height:auto;">`,
                multiimage: v => processMultiImage(v),
                file: v => `${getExtension(v)}附件`,
                word: v => `${getExtension(v)}附件`,
                multifile: v => `${JSON.parse(v).length}个附件`,
                video: v => `${JSON.parse(v).length}个视频`,
                subtable: v => processSubtable(v),
                default: v => window.validators.isJSON(v) ? parsedValue(v) : v
            }
            return processors[type]?.(value) ?? processors.default(value);
        }
        
        const processImage = async url => (await isImageValid(url)) ? `<img src="${url}" style="width:50px;height:auto;">` : '';
        
        //处理多图
        const processMultiImage = async (value) => {
            let parsedValue = window.validators.isJSON(value) ? JSON.parse(value) : value;
            if (Array.isArray(parsedValue)) {
                const images = await Promise.all(parsedValue.map(img => processImage(img || '')));
                return images.join('');
            }
        };
        
        //处理子表
        const processSubtable = value => {
            let data = window.validators.isJSON(value) ? JSON.parse(value) : value;
            return data.length ? generateTableHtml(Object.keys(data[0]).map(k => ({ field: k, displayName: k })), data, '') : '';
        }
        
        const print = (html, align, name) => {
            window.printJS({
                printable: html,
                type: 'raw-html',
                documentTitle: `打印者：${name}`,
                style: `table{width:100%;border-collapse:collapse;font-size:12px;}
                th,td{border:1px solid #373232;padding:5px;text-align:${align};max-width:150px;}`
            })
        }
        
        //水印
        const generateWatermark = text => {
            return `
            <div style="position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:-1;opacity:0.06;">
                ${Array.from({ length: 25 }, (_, i) => {
                    const rotate = -45 + Math.random() * 15;
                    const posX = Math.random() * 100;
                    const posY = Math.random() * 100;
                    return `<div style="
                        position:absolute;
                        top:${posY}%;
                        left:${posX}%;
                        transform:rotate(${rotate}deg);
                        color:#666;
                        font-size:28px;
                        white-space:nowrap;
                    ">${text}</div>`
                }).join('')}
            </div>`;
        }
        
        const isImageValid = url => new Promise(resolve => {
            const img = new Image()
            img.onload = () => resolve(true)
            img.onerror = () => resolve(false)
            img.src = url
        });
        
        const getExtension = name => name.split('.').pop();
        const parsedValue = value => window.validators.isJSON(value) ? JSON.parse(value).join(', ') : '';
        
    	// 生成表格 HTML 的函数
        const generateTableHtml = (headers, datasj, xmmc) => {
            if (!Array.isArray(datasj)) {
                console.error('Invalid data format:', datasj);
                datasj = [];
            }
            let html = xmmc ? `<div style="text-align:center;font-size:20px;margin:25px 0;font-weight:bold;border-bottom:2px solid #ddd;padding-bottom:10px;">${xmmc}</div>` : '';
            html += `
                <table>
                    <thead>
                        <tr>
                            ${headers.map(h => `<th>${h.displayName}</th>`).join('')}
                        </tr>
                    </thead>
                    <tbody>
                        ${datasj.length ? 
                            datasj.map(data => `
                                <tr>
                                    ${headers.map(h => `
                                        <td>${data[h.field] || ''}</td>
                                    `).join('')}
                                </tr>
                            `).join('') : 
                            `<tr><td colspan="${headers.length}" style="text-align:center;color:#999;">暂无数据</td></tr>`}
                    </tbody>
                </table>
            `;
            return html;
        }
        
        // 显式暴露方法
        expose({
            tablePrint,
        });
        
        return {
            tablePrint,
            generateHeaders,
            processData,
            processFieldValue,
            processImage,
            processMultiImage,
            processSubtable,
            print,
            user,
            generateWatermark,
            isImageValid,
            getExtension,
            parsedValue,
            generateTableHtml
        }
        
    },
    
    template: `<div style="margin:10px 0px;"></div>`
}